import { LessThan, Repository, Between } from 'typeorm';
import { Injectable, InternalServerErrorException } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { GenerateUUID } from '@/utils/uuid';
import {
  ERROR_INVITATION_CODE,
  ERROR_ORDER_NOT_EXISTS,
} from '@/common/constant';
import {
  PayForCouponDto,
  PayForTaskDto,
  PayForTokenDto,
  PayForVipDto,
  RefundDto,
} from './dto/create-order.dto';
import { Order, OrderStatus } from './entities/order.entity';
import { WepayService } from '../wepay/wepay.service';
import { UserService } from '../user/user.service';
import configuration from 'config/configuration';
import { UpdateOrderDto } from './dto/update-order.dto';
import { Coupon } from '../coupon/entities/coupon.entity';
import { CouponService } from '../coupon/coupon.service';

@Injectable()
export class OrderService {
  constructor(
    @InjectRepository(Order)
    private readonly orderRepository: Repository<Order>,
    private readonly couponService: CouponService,
    private readonly wepayService: WepayService,
    private readonly userService: UserService,
  ) { }

  async createVipOrderMock(payforVipDto: PayForVipDto) {
    // 校验邀请码正确性
    let inviteUser: any;
    if (payforVipDto.invitationCode) {
      inviteUser = await this.userService.findOneByOpenId(
        payforVipDto.invitationCode,
      );
      if (!inviteUser)
        throw new InternalServerErrorException(ERROR_INVITATION_CODE);
    }
    // 给用户添加token和vip状态，如果有人邀请，给邀请人发送奖励
    await Promise.all([
      this.userService.becomeVip(payforVipDto.userId),
      inviteUser
        ? this.userService.sendInviteReward(inviteUser.id)
        : Promise.resolve(),
    ]);
  }

  async createTokenOrder(payForTokenDto: PayForTokenDto) {
    const order = await this.orderRepository.save(new Order(payForTokenDto));
    const user = await this.userService.Detail(order.userId);
    const prepayId = await this.wepayService.CreateOrderWX({
      id: order.id,
      price: order.price,
      description: `${user.phone}的订单`,
      openId: user.openId,
      callbackUrl: `${configuration.domain}/order/callback/payfor/token`,
    });
    order.prepayId = prepayId;
    return await this.orderRepository.save(order);
  }

  async payForTokenSuccess(orderId: string) {
    const [, order] = await Promise.all([
      this.update(orderId, {
        status: OrderStatus.PAID,
        payTime: new Date(),
      }),
      this.orderRepository.findOneBy({ id: orderId }),
    ]);
  }

  async createOrder(payforTaskDto: PayForTaskDto) {
    const createOrderDto = new Order(payforTaskDto);
    createOrderDto.price = payforTaskDto.orderAmount;
    // 设置takerFinishTime为当前时间前一天
    createOrderDto.takerFinishTime = new Date(new Date().getTime() - 1 * 24 * 60 * 60 * 1000);

    const order = await this.orderRepository.save(createOrderDto);
    return order;
  }

  async getPrepayId(payforCouponDto: PayForCouponDto) {
    const order = await this.orderRepository.findOneBy({ id: payforCouponDto.orderId });
    const coupon = await this.couponService.Detail(payforCouponDto.couponId);
    let price = coupon.UseCoupon(order.orderAmount);

    // 如果优惠后价格小于等于0，设置为0.01元，避免微信支付失败
    if (price <= 0) {
      price = 0.01;
    }

    const user = await this.userService.Detail(order.userId);
    console.log("info", {
      id: order.id,
      price: price, // 单位元
      description: `${user.phone}的订单`,
      openId: user.openId,
      callbackUrl: `${configuration.domain}/api/order/callback/payfor/vip`,
    });
    const prepayId = await this.wepayService.CreateOrderWX({
      id: order.id,
      price: price, // 单位元
      description: `${user.phone}的订单`,
      openId: user.openId,
      callbackUrl: `${configuration.domain}/api/order/callback/payfor/vip`,
    });
    order.prepayId = prepayId;
    console.log("order", order);
    return await this.orderRepository.save(order);
  }

  async createVipOrder(payforVipDto: PayForVipDto) {
    // // 校验邀请码正确性
    // if (payforVipDto.invitationCode) {
    //   const inviteUser = await this.userService.findOneByOpenId(
    //     payforVipDto.invitationCode,
    //   );
    //   if (!inviteUser)
    //     throw new InternalServerErrorException(ERROR_INVITATION_CODE);
    // }
    const order = await this.orderRepository.save(new Order(payforVipDto));
    const user = await this.userService.Detail(order.userId);
    const prepayId = await this.wepayService.CreateOrderWX({
      id: order.id,
      price: order.price, // 单位元
      description: `${user.phone}的订单`,
      openId: user.openId,
      callbackUrl: `${configuration.domain}/order/callback/payfor/vip`,
    });
    order.prepayId = prepayId;
    return await this.orderRepository.save(order);
  }

  async payForVipSuccess(orderId: string) {
    // 更新订单状态，获取订单信息
    const [, order] = await Promise.all([
      this.update(orderId, {
        status: OrderStatus.PAID,
        payTime: new Date(),
      }),
      this.orderRepository.findOneBy({ id: orderId }),
    ]);
    // 查询邀请的用户
    // const inviteUser = await this.userService.findOneByOpenId(
    //   order.invitationCode,
    // );
    // 给用户添加token和vip状态，如果有人邀请，给邀请人发送奖励
    // await Promise.all([
    //   this.userService.becomeVip(order.userId),
    //   inviteUser
    //     ? this.userService.sendInviteReward(inviteUser.id)
    //     : Promise.resolve(),
    // ]);
  }

  async refund(refundDto: RefundDto) {
    const order = await this.orderRepository.findOneBy({ id: refundDto.id });
    if (!order) throw new InternalServerErrorException(ERROR_ORDER_NOT_EXISTS);
    order.refundId = GenerateUUID();
    order.refundTime = new Date();
    order.status = OrderStatus.REFUNDING;
    const result = await this.wepayService.RefundedOrderWX({
      id: order.id,
      refundId: order.refundId,
      totalPrice: order.price,
      refundPrice: order.price,
      callbackUrl: '',
    });
    if (result) await this.orderRepository.save(order);
  }

  async refundSuccess(refundId: string) {
    const order = await this.orderRepository.findOneBy({ refundId: refundId });
    if (!order) throw new InternalServerErrorException(ERROR_ORDER_NOT_EXISTS);
    order.status = OrderStatus.REFUNDED;
    return await this.orderRepository.save(order);
  }

  update(id: string, updateOrderDto: UpdateOrderDto) {
    return this.orderRepository.update(id, updateOrderDto);
  }

  // 查询单条
  async Detail(id: string) {
    const order = await this.orderRepository.findOneBy({ id });
    console.log("order", order);

    // 确保imageList始终是数组
    if (order) {
      if (order.imageList && typeof order.imageList === 'string') {
        try {
          order.imageList = JSON.parse(order.imageList);
        } catch (e) {
          order.imageList = [];
        }
      } else if (!order.imageList) {
        order.imageList = [];
      }
    }

    return order;
  }

  // 查询列表
  async List(id: string) {
    try {
      const orderList = await this.orderRepository.find({
        where: { userId: id },
        order: {
          createTime: 'DESC',
        },
      });

      // 确保imageList始终是数组
      return orderList.map(order => {
        try {
          if (order.imageList) {
            if (typeof order.imageList === 'string') {
              order.imageList = JSON.parse(order.imageList);
            } else if (!Array.isArray(order.imageList)) {
              order.imageList = [];
            }
          } else {
            order.imageList = [];
          }
        } catch (e) {
          console.error('处理订单图片列表出错:', e);
          order.imageList = [];
        }
        return order;
      });
    } catch (error) {
      console.error('获取订单列表出错:', error);
      throw error;
    }
  }

  // 管理员查询今日待完成列表列表
  async ListByGlyToday(orderType: string) {
    const today = new Date();
    today.setHours(0, 0, 0, 0);

    const orderList = await this.orderRepository.find({
      where: {
        status: OrderStatus.PAID,
        orderType: orderType,
        takerFinishTime: LessThan(today)
      },
      order: {
        createTime: 'DESC',
      },
    });
    return orderList;
  }

  // 管理员查询列表
  async ListByGly(orderType: string) {
    // 查询所有已支付（进行中）且当天0点前未完成的订单（takerFinishTime）或者没有takerFinishTime的订单
    // 当天0点时间：
    const today = new Date();
    today.setHours(0, 0, 0, 0);
    const orderList = await this.orderRepository.find({
      where: { status: OrderStatus.PAID, orderType: orderType, takerFinishTime: LessThan(today) },
      order: {
        createTime: 'DESC',
      },
    });
    return orderList;
  }

  // 管理员查询完成列表
  async ListByGlyAndFinishTime(orderType: string) {
    const orderList = await this.orderRepository.find({
      where: { orderType: orderType },
      order: {
        takerFinishTime: 'DESC',
      },
    });
    return orderList;
  }

  // 管理员完成任务
  async FinishTask(userId: string, orderId: string) {
    console.log("userId", userId);
    console.log("orderId", orderId);
    const order = await this.orderRepository.findOneBy({ id: orderId });
    order.takerFinishTime = new Date();
    order.takerUserId = userId;
    // 如果订单有结束时间，则先判断当前时间是否大于结束日期的0点
    console.log("order", order);
    if (order.timeEnd) {
      const timeEnd = new Date(order.timeEnd);
      const now = new Date();
      if (now.getTime() > timeEnd.getTime()) {
        order.status = OrderStatus.FINISHED;
      }
    } else {
      order.status = OrderStatus.FINISHED;
    }

    return await this.orderRepository.save(order);
  }

  // findAll() {
  //   return `This action returns all order`;
  // }

  // findOne(id: number) {
  //   return `This action returns a #${id} order`;
  // }

  // remove(id: number) {
  //   return `This action removes a #${id} order`;
  // }
}
